package client;

import java.io.IOException;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Hashtable;

import event.Event;
import event.EventHandler;

/*
 * A history of active and past downloads.
 */
public class DownloadManager implements Serializable {

	private static final long serialVersionUID = -4856348823270328891L;

	private Hashtable<String, Download> mDownloads = new Hashtable<String, Download>();

	private DownloadTableModel model;
	
	private final ClientController controller;

	public DownloadManager(ClientController controller,
			DownloadTableModel model) {
		this.controller = controller;
		this.model = model;
	}

	public DownloadTableModel getTableModel() {
		return model;
	}

	public void addDownload(Download download) {
		download.setTableModel(model);

		synchronized (this) {
			model.addRow(new Object[] { download.remoteFile, "",
					download.getProgress() });

			download.row = model.getRowCount() - 1;
		}

		mDownloads.put(download.remoteFile, download);
	}

	public void download(Download download) {
		try {
			ComPeer comPeer = new ComPeer(InetAddress.getByName(download.url),
					8181, controller.mPeerEventManager);

			new Thread(comPeer).start();

			download.setDownloader(comPeer);
			download.start();

			comPeer.request(download.remoteFile, download.getProgress());
		} catch (IOException e1) {
			download.pause();
		}
	}

	public void pauseDownload(Download download) {
		download.pause();
	}

	public Download getDownload(String url) {
		return mDownloads.get(url);
	}

	public Collection<Download> getDownloads() {
		return mDownloads.values();
	}

	public void removeDownload(String url) {
		mDownloads.remove(url);
	}

}
